package cn.hamster3.mc.plugin.core.velocity.impl;

import cn.hamster3.mc.plugin.core.velocity.HamsterCorePlugin;
import com.velocitypowered.api.proxy.Player;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.text.flattener.ComponentFlattener;
import org.jetbrains.annotations.NotNull;

import java.util.UUID;

public class AudienceProviderImpl implements AudienceProvider {
    public static final AudienceProviderImpl INSTANCE = new AudienceProviderImpl();

    private AudienceProviderImpl() {
    }

    @Override
    public @NotNull Audience all() {
        return Audience.audience(console(), players());
    }

    @Override
    public @NotNull Audience console() {
        return HamsterCorePlugin.getInstance().getProxyServer().getConsoleCommandSource();
    }

    @Override
    public @NotNull Audience players() {
        return Audience.audience(HamsterCorePlugin.getInstance().getProxyServer().getAllPlayers());
    }

    @Override
    public @NotNull Audience player(@NotNull UUID playerId) {
        Player player = HamsterCorePlugin.getInstance().getProxyServer().getPlayer(playerId).orElse(null);
        if (player == null) {
            return Audience.empty();
        }
        return player;
    }

    @Override
    public @NotNull Audience permission(@NotNull String permission) {
        return Audience.audience(
                HamsterCorePlugin.getInstance().getProxyServer().getAllPlayers()
                        .stream()
                        .filter(player -> player.hasPermission(permission))
                        .toList()
        );
    }

    @Override
    public @NotNull Audience world(@NotNull Key world) {
        return Audience.empty();
    }

    @Override
    public @NotNull Audience server(@NotNull String serverName) {
        return Audience.audience(
                HamsterCorePlugin.getInstance().getProxyServer().getAllPlayers()
                        .stream()
                        .filter(player -> player.getCurrentServer()
                                .map(o -> o.getServerInfo().getName().equals(serverName))
                                .orElse(false)
                        ).toList()
        );
    }

    @Override
    public @NotNull ComponentFlattener flattener() {
        return ComponentFlattener.basic();
    }

    @Override
    public void close() {

    }
}
